package com.kawa.es.controller;

import com.kawa.es.domain.CloudDiskEntity;
import com.kawa.es.repository.CloudDiskRepository;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.MatchQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.web.PageableDefault;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.Optional;

// SpringBoot 整合ES增删改查
@RestController
public class CloudDiskController {

    @Autowired
    private CloudDiskRepository cloudDiskDao;

    @GetMapping("/findById/{id}")
    public Optional<CloudDiskEntity> findById(@PathVariable String id) {
        return cloudDiskDao.findById(id);
    }

    // page 表示请求的页数 从0开始
    // value size 每一页展示多少条数据
    // @PageableDefault 默认值
    @GetMapping("/search")
    public String search(String keyword, @PageableDefault(page =
            0, value = 2) Pageable pageable, HttpServletRequest req) {
        // 查询所有的
        BoolQueryBuilder boolQuery = QueryBuilders.boolQuery();
        if (!StringUtils.isEmpty(keyword)) {
            // 模糊查询 一定要ik中文
            MatchQueryBuilder matchQuery = QueryBuilders.matchQuery("name", keyword);
            boolQuery.must(matchQuery);
        }
        Page<CloudDiskEntity> page = cloudDiskDao.search(boolQuery, pageable);
        // 计算分页总数
        int totalPage = (int) ((page.getTotalElements() - 1) / pageable.getPageSize() + 1);
        req.setAttribute("page", page);
        // 当前页数
        req.setAttribute("pageNumber", pageable.getPageNumber());
        // 标题名称 关键字
        req.setAttribute("keyword", keyword);
        // 分页总数
        req.setAttribute("totalPage", totalPage);
        return "search";
    }

}
